﻿using JYH.Business;
using JYH.Model.API;
using JYH.Model;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using JYH.Data;
using FastReport;
using System.IO;
using JYH.Framework;
using System.Web.Hosting;
using System.Data;
using System.Threading.Tasks;
using FastReport.Export.Pdf;
using System.Web.UI.WebControls;
using FastReport.Data;

namespace JYH.Web.MES.Controllers
{
    public class WINController : ApiController
    {


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public IHttpActionResult Login([FromBody] dynamic info)
        {
            ResponseJson<SysUserInfo> json = new ResponseJson<SysUserInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<SysUserInfo>();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                SysUserInfo obj = new SysUserInfo();

                obj.UserNO = info.UserNO;
                obj.Pwd = info.Pwd;
                SysUserInfoBLL bLL = new SysUserInfoBLL();

                SysUserInfo user = bLL.Login(obj, out Msg);

                if (user != null)
                {
                    json.Items.Add(user);
                }
                else
                {
                    json.Code = 500;
                    json.Message = Msg;
                    return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<SysUserInfo>();
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
            return Ok(JsonConvert.SerializeObject(json));
        }


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public IHttpActionResult GetSingleMaterial([FromBody] dynamic info)
        {
            ResponseJson<BasMaterialInfo> json = new ResponseJson<BasMaterialInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<BasMaterialInfo>();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                BasMaterialInfo obj = new BasMaterialInfo();

                obj.MaterialNO = info.MaterialNO;
                Sql sql = new Sql();
                sql.Where("BasMaterialInfo.MaterialNO='" + obj.MaterialNO + "'");
                BasMaterialInfoBLL bLL = new BasMaterialInfoBLL();

                BasMaterialInfo material = bLL.GetSingeModel(sql);

                if (material != null)
                {
                    json.Items.Add(material);
                }
                else
                {
                    json.Code = 500;
                    json.Message = Msg;
                    return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<BasMaterialInfo>();
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
            return Ok(JsonConvert.SerializeObject(json));
        }


        /// <summary>
        /// 获取单个物料标签条码信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public IHttpActionResult GetSingleBarcode([FromBody] dynamic info)
        {
            ResponseJson<BasBarcodeInfo> json = new ResponseJson<BasBarcodeInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<BasBarcodeInfo>();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {
                BasBarcodeInfo obj = new BasBarcodeInfo();

                obj.BarcodeNO = info.BarcodeNO;

                BasBarcodeInfoBLL bLL = new BasBarcodeInfoBLL();

                Sql sql = new Sql();
                sql.Where("BasBarcodeInfo.BarcodeNO='" + obj.BarcodeNO + "'");


                BasBarcodeInfo barcode = bLL.GetSingeModel(sql);

                if (barcode != null)
                {
                    json.Items.Add(barcode);
                }
                else
                {
                    json.Code = 500;
                    json.Message = Msg;
                    return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
                }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<BasBarcodeInfo>();
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
            return Ok(JsonConvert.SerializeObject(json));
        }


        /// <summary>
        /// 新增条码信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [EnableCors("AllowSpecificOrigin")]
        [HttpPost]
        public IHttpActionResult AddNewwBarcode([FromBody] dynamic info)
        {
            ResponseJson<BasBarcodeInfo> json = new ResponseJson<BasBarcodeInfo>();
            json.Code = 200;
            json.Message = string.Empty;
            json.Items = new List<BasBarcodeInfo>();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, json);

            try
            {

                List<BasBarcodeInfo> list = new List<BasBarcodeInfo>();

          string Json= JsonConvert.SerializeObject(info);
                BasBarcodeInfo obj = JsonConvert.DeserializeObject<BasBarcodeInfo>(Json);
                
                list.Add(obj);

                       BasBarcodeInfoBLL bLL = new BasBarcodeInfoBLL();

          


               bLL.SaveBarcodeInfo(list, ref json);

                
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                json.Items = new List<BasBarcodeInfo>();
                return Content(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(json));
            }
            return Ok(JsonConvert.SerializeObject(json));
        }



        [HttpPost]
        [EnableCors("AllowSpecificOrigin")]
        public IHttpActionResult PrintWithFastReport([FromBody] List<BasBarcodeInfo> info)
        {
            string Msg=string.Empty;
            try
            {
                // 1. 加载 FastReport 模板
                using (Report report = new Report())
                {

                    SysParaInfo paraInfo = new SysParaInfo();
                    paraInfo = SysParaInfoBLL.GetParaInfo("MaterialBarcode", out Msg);
                    string BarcodeLable = "MaterialBarcode";
                    if (paraInfo != null)
                    {
                        BarcodeLable = paraInfo.ParaValue;
                    }
                    string reportPath = HostingEnvironment.MapPath("~/App_Data/Lable/" + BarcodeLable + ".frx");

                    if (!File.Exists(reportPath))
                    {
                        return NotFound();
                    }

                    report.Load(reportPath);
                    DataSet ds = new DataSet();
                    string NO = "'',";
                    foreach (var row in info) 
                    {
                        NO += "'"+row.BarcodeNO+"',";
                    }
                    NO=NO.Substring(0,NO.Length-1);
                    Sql sql= new Sql();
                    BasBarcodeInfoBLL bll = new BasBarcodeInfoBLL();
                    sql.Append(bll.SqlSelect);
                    sql.Where("BasBarcodeInfo.BarcodeNO in (" + NO + ")");
                    bll.myDataBase.Fill(ds,sql.SQL,null);

                    if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count < 1)
                    {
                        return NotFound();
                    }
                    ds.Tables[0].TableName = "BasBarcodeInfo";
                    //foreach (DataSourceBase dd in report.Dictionary.DataSources)
                    //{
                    //    dd.Enabled = false;
                    //}
                    //report.Dictionary.DataSources.Clear();
                    // 2. 注册数据

                    report.RegisterData(ds);
                    report.GetDataSource("BasBarcodeInfo").Enabled = true;
                    report.Refresh();

                    report.Dictionary.Connections[0].ConnectionString = ConfigHelper.GetConnectionString("DBCONN");
                  
   
                    //report.Report.GetDataSource("BasBarcodeInfo").Enabled = true;
                    //report.GetDataSource("BasBarcodeInfo").Enabled = true;
                    //foreach (DataSourceBase vd in report.Dictionary.DataSources)
                    //{
                    //    Console.WriteLine($"Data Source: {vd.Name}, Enabled: {vd.Enabled}");
                    //}
                    ////  report.Report.Dictionary.Connections[0].ConnectionString = ConfigHelper.GetConnectionString("DBCONN");
                    report.Prepare();
                    //report.Report.Prepare(); // 确保数据准备完成


                    // 3. 准备打印

                    byte[] reportBytes;
                    //using (var ms = new MemoryStream())
                    //{
                    //    report.Export(new PDFExport(), ms);
                    //    reportBytes= ms.ToArray();
                    //}

                    using (var ms = new MemoryStream())
                    {
                        report.Save(ms);  // 保存为原生格式
                        reportBytes = ms.ToArray();
                    }
                    if (reportBytes.Length < 1)
                    {
                        return NotFound();
                    }

                    return Ok(new ApiResponse
                    {
                        Success = true,
                        ReportData = Convert.ToBase64String(reportBytes),
                        Data = JsonConvert.SerializeObject(ds)

                    });
                    //return Ok(new { ReportData = Convert.ToBase64String(reportBytes) });
                    // 4. 直接打印到默认打印机
                  
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, new ApiResponse
                {
                    Success = false,
                    Message = ex.Message
                });
            }
        }


   
    }
}